package com.java.example.jpush

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Build
import android.os.IBinder
import com.java.example.R
import com.java.example.app.Latte
import com.java.example.bean.EventType
import com.java.example.bean.MessageEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.IOException

class AudioService : Service() {
    var isPlay: Boolean = false
    var stageId: Int = 0
    private var content: String? = null

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        val resId = intent.getIntExtra("audio", 0)
        content = intent.getStringExtra("content")
        if (resId != 0) {
            EventBus.getDefault().post(MessageEvent(EventType.PLAY_AUDIO, AudioEventBean(resId, stageId)))
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onCreate() {
        super.onCreate()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notification: Notification
            //新增---------------------------------------------
            val CHANNEL_ONE_ID = "com.java.example"
            val CHANNEL_ONE_NAME = "Channel One"
            var notificationChannel: NotificationChannel? = null
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notificationChannel = NotificationChannel(
                        CHANNEL_ONE_ID,
                        CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_NONE
                )
                notificationChannel.enableLights(false)
                notificationChannel.lightColor = Color.RED
                notificationChannel.setShowBadge(false)
                notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
                val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
                manager.createNotificationChannel(notificationChannel)
            }

            //--------------------------------------------------------新增
            val intent = Intent(this, MyReceiver::class.java)
            val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
            notification = Notification.Builder(this, CHANNEL_ONE_ID).setChannelId(CHANNEL_ONE_ID)
                .setTicker("Nature")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("旺材")
                .setContentText(content)
                .setContentIntent(pendingIntent)
                .build()
            notification.flags = notification.flags or Notification.FLAG_NO_CLEAR
            startForeground(1, notification)
        }
        EventBus.getDefault().register(this)
    }

    private fun initMediaPlay() {
//        AssetFileDescriptor assetFileDescriptor = Latte.getApplicationContext().getResources().openRawResourceFd(R.raw.m_common);
        //            mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor());
//            mediaPlayer.prepare();
        mediaPlayer!!.setOnCompletionListener {
            isPlay = false
            mediaPlayer!!.release()
            mediaPlayer = null
            EventBus.getDefault().post(MessageEvent(EventType.AUDIO_PLAY_FINISH, stageId))
            stopSelf()
        }
        mediaPlayer!!.setOnErrorListener { mp, what, extra ->
            isPlay = false
            stopSelf()
            false
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    fun handleEvent(event: MessageEvent) {
        when (event.type) {
            EventType.PLAY_AUDIO -> {
                val eventBean = event.obj as AudioEventBean?
                val finalRestId = eventBean!!.resId
                stageId = eventBean.stageId
                if (isPlay) return
                mediaPlayer = MediaPlayer
                    .create(Latte.applicationContext, finalRestId)
                initMediaPlay()
                try {
                    //在播放之前先判断playerMusic是否被占用，这样就不会报错了

                    if (mediaPlayer != null) {
                        mediaPlayer!!.stop()
                    }
                    mediaPlayer!!.prepare()
                    mediaPlayer!!.start()
                    isPlay = true
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (mediaPlayer != null) {
            mediaPlayer!!.stop()
            mediaPlayer!!.release()
        }
        EventBus.getDefault().unregister(this)
    }

    companion object {
        var mediaPlayer: MediaPlayer? = null
    }
}
